//
//  PrescriptionOrderPayResultController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2023/1/9.
//  Copyright © 2023 QDSG. All rights reserved.
//

import UIKit

enum PrescriptionOrderPayResultType {
    case waiting
    case success
    case failuer
    
    var icon: UIImage? {
        switch self {
        case .waiting:
            return UIImage(named: "pay_medicalInsurance_wait")
        case .success:
            return UIImage(named: "pay_medicalInsurance_success")
        case .failuer:
            return UIImage(named: "pay_medicalInsurance_failure")
        }
    }
    
    var title: String {
        switch self {
        case .waiting: return "订单结果确认中..."
        case .success: return "支付成功"
        case .failuer: return "支付失败"
        }
    }
}

class PrescriptionOrderPayResultController: CLBaseViewController {
    let orderId: String
    let preId: String
    init(orderId: String,
         preId: String) {
        self.orderId = orderId
        self.preId = preId
        super.init()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var model:PrescriptionOrderDetail? {
        didSet {
            type = (model?.status == .waitShip || model?.status == .waitTake) ? .success : .waiting
            successView.model = model
        }
    }
    var type: PrescriptionOrderPayResultType = .waiting {
        didSet {
            waitView.isHidden = true
            successView.isHidden = true
            icon.image = type.icon
            tips.text = type.title
            switch type {
            case .success:
                action.isHidden = false
                action.snp.remakeConstraints { make in
                    make.centerX.equalToSuperview()
                    make.left.equalTo(30)
                    make.right.equalTo(-30)
                    make.height.equalTo(50)
                    make.top.equalTo(successView.snp.bottom).offset(40)
                }
                successView.isHidden = false
            case .waiting:
                waitView.isHidden = false
                action.snp.remakeConstraints { make in
                    make.left.equalTo(30)
                    make.right.equalTo(-30)
                    make.height.equalTo(50)
                    make.top.equalTo(waitView.snp.bottom).offset(40)
                }
            case .failuer:
                action.isHidden = false
                action.snp.remakeConstraints { make in
                    make.centerX.equalToSuperview()
                    make.left.equalTo(30)
                    make.right.equalTo(-30)
                    make.height.equalTo(50)
                    make.top.equalTo(tips.snp.bottom).offset(40)
                }
            }
        }
    }
    
    let icon = UIImageView(image: UIImage(named: "pay_medicalInsurance_wait"))
    let tips = UILabel()
    let successView = PrescriptionOrderPayResultSuccessView()
    let waitView = PrescriptionOrderPayResultWaitView()
    let action = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .init(hex: "#F8F8F8")
        title = "支付结果"
        
        view.addSubview(icon)
        icon.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(clSafeAreaInsets.top)
        }
        
        view.addSubview(tips)
        tips.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(icon.snp.bottom).offset(16)
        }
        tips.font = .medium_18
        tips.textColor = .init(hex: "#333333")
        tips.text = "订单结果确认中..."
        
        view.addSubview(waitView)
        waitView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(tips.snp.bottom).offset(16)
        }
        
        view.addSubview(successView)
        successView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(tips.snp.bottom).offset(16)
        }
        successView.isHidden = true
        
        view.addSubview(action)
        action.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
        }
        action.isHidden = true
        action.setTitle("返回订单页面", for: .normal)
        action.backgroundColor = .mainColor
        action.titleLabel?.font = .medium_16
        action.layer.cornerRadius = 25
        action.layer.masksToBounds = true
        action.addTarget(self, action: #selector(actionClick), for: .touchUpInside)
        
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(receiveMessage(_:)), name: NotiName.receiveMessage, object: nil)
    }
    
    @objc func receiveMessage(_ noti: Notification) {
        guard let message = noti.object as? String,
              let receiveModel = ReceiveModel.deserialize(from: message) else { return }
        
        if receiveModel.preId != preId {
            return
        }
        switch receiveModel.cmd {
        case 114:
            loadData()
        case 115:
            self.type = .failuer
        default: break
        }
    }
    
    @objc func applicationDidBecomeActive() {
        loadData()
    }
    
    func loadData() {
        HttpTool.shared.request(api: ApiManager.prescriptionOrderDetail(orderId: orderId), model: PrescriptionOrderDetail.self, completeHandle: {
            switch $0 {
            case .success(let model):
                self.model = model.data
            case .failure(let error):
                error.showToast()
            }
        })
    }
    
    @objc func actionClick() {
        switch type {
        case .waiting: break
        case .success:
            let vc = navigationController?.viewControllers.first(where: { $0.isKind(of: ChatViewController.self) }) as? ChatViewController
            vc?.loadData()
            navigationController?.popViewController(viewControllerType: ChatViewController.self)
        case .failuer:
            navigationController?.popViewController(animated: true)
        }
    }
}

extension UINavigationController {
    func popViewController<T: UIViewController>(viewControllerType: T.Type) {
        if let vc = viewControllers.first(where: { $0.isKind(of: viewControllerType.classForCoder() )}) {
            popToViewController(vc, animated: true)
        } else {
            popViewController(animated: true)
        }
    }
}
